#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.


# -*- coding: UTF-8 -*-
import json
import requests
from warnings import catch_warnings
from flask import current_app as app
from extensions.exception import FceException

import common_libs.localrun as localrun

class CommonService():
    isLocal = False
    def __init__(self):
        return

    def exec_local(self, cmd, timeout=10):
        (status, response) = localrun.run(cmd, timeout)
        if status < 0:
            FceException('Timeout.FceutilCommand', cmd)
        elif status > 0:
            FceException('OperationFailed.FceutilCommand', cmd, response)

        return response 
    def exec_fceutil(self, cmd, timeout=10):
        fce_util_local_path = app.config.get('FCEUtil_BIN')
        command_str = "%s %s" % (fce_util_local_path, cmd)
        ret_data = None

        res = self.exec_local(command_str, timeout)
        try:
            ret_data = json.loads(res)
        except Exception as e:
            FceException('InvalidDataType.FceutilResult', e)
        
        if ret_data["Success"] == False:
            FceException('OperationFailed.FceutilCommand', cmd.split()[0], ret_data["Message"])
        return ret_data["Message"]
    
    def exec_fceutil_cmd(self, cmd, timeout=10):
        fce_util_local_path = app.config.get('FCEUtil_BIN')
        command_str = "%s %s" % (fce_util_local_path, cmd)
        res = self.exec_local(command_str, timeout)
        #app.logger.info("run res:{}".format(res))
        try:
            ret_data = json.loads(res)
        except Exception as e:
            FceException('InvalidDataType.FceutilResult', e)

        return ret_data

    def get_meta_data(self, key):
        url = 'http://100.100.100.200/latest/meta-data/%s' % key
        headers = {'content-type': 'application/json'}
        return str(requests.get(url, headers=headers).content, encoding='utf-8')